/**
 * @author harry
 * @date 2022/2/7/22:28
 */

package com.serviceOrchestration.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisDao {
    public static final String TOKEN_KEY_PREFIX = "token:";

    private final StringRedisTemplate redisTemplate;

    @Autowired
    public RedisDao(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public String get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public void set(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public void expire(String key, long time) {
        redisTemplate.expire(key, time, TimeUnit.MILLISECONDS);
    }

    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.MILLISECONDS);
    }

    /**
     * 新增并设置过期时间
     * @param expiration 单位ms
     */
    public void setAndExpire(String key, String value, long expiration) {
        redisTemplate.opsForValue().set(key, value, expiration, TimeUnit.MILLISECONDS);
    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }

    public boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }
}
